﻿using System;
using System.Diagnostics;
using System.Security.Policy;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SqlSugar;

namespace 请求响应加密.Middle
{
    public class ExceptionHandle
    {
        private readonly RequestDelegate _next;
        private readonly ISqlSugarClient DB;
        private readonly IConfiguration _configuration;
        private readonly ILogger<ExceptionHandle> logger;

        public ExceptionHandle(IConfiguration configuration,RequestDelegate next, ILogger<ExceptionHandle> logger)
        {
            _configuration = configuration;
            _next = next;
            this.logger = logger;
            DB = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = _configuration.GetValue<string>("ConnectionStrings:url"),
                DbType = DbType.MySql,
                IsAutoCloseConnection = true
            });
        }

        public async Task Invoke(HttpContext context)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
          
            ApiAccessLog model = new ApiAccessLog() // 36行
            {
                Url = context.Request.Path.Value ?? "",
                Method = context.Request.Method,
                QueryString = context.Request.QueryString.Value ?? "",
                OriginIP = context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
                AccessTime = DateTime.Now,
            };
            try
            {
                await _next.Invoke(context);
            }
            catch (Exception ex)
            {
                model.Msg = ex.Message;
                logger.LogError(ex.Message);
                byte[] errMsgBytes = Encoding.UTF8.GetBytes(ex.Message);
                Stream stream = context.Response.Body;
                context.Response.StatusCode = 500;
                context.Response.ContentLength = errMsgBytes.Length;
                await stream.WriteAsync(errMsgBytes);
                context.Response.Body = stream;
            }
            finally 
            {
                stopwatch.Stop();
                // 毫秒
                long timeCount = stopwatch.ElapsedMilliseconds;
                model.StatusCode = context.Response.StatusCode;
                model.ExecuteTime = timeCount;
                await DB.Insertable<ApiAccessLog>(model).ExecuteCommandAsync();
            }
        }
    }
}
